/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wii.elpro.web.action;

import com.wii.elpro.dao.jpa.ProdukDAOImpl;
import com.wii.elpro.entity.Produk;
import com.wii.elpro.entity.ProdukMaterial;
import com.wii.elpro.entity.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Vyor
 */
public class ProdukRemoveMaterialsAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        try {
            ProdukDAOImpl dao = new ProdukDAOImpl();
            Produk p = dao.getProduk(Long.parseLong(request.getParameter("idProd")));
            Produk material = dao.getProduk(Long.parseLong(request.getParameter("id")));
            int posisi = 0;
            for (int i = 0 ; i < p.getProdukMaterials().size(); i++) {
                if(((ProdukMaterial)p.getProdukMaterials().get(i)).getMaterial().getId() == material.getId()){
                    posisi = i;
                    break;
                }
            }
            p.getProdukMaterials().remove(posisi);
            
            dao.update(p);
            
            request.setAttribute("prod", dao.getProduk(Long.parseLong(request.getParameter("idProd"))));
            
            forward = "success";
        } catch (Exception e) {
            forward = "fail";
        }
        return mapping.findForward(forward);
    }
}
